#pragma once

#include <pthread.h>
#include <functional>
#include <string>

namespace ThreadMoudle
{
    using func_t = std::function<void(std::string&)>;
    class Thread
    {
    private:
        void Excute()
        {
            _isRuning = true;
            _fun(_name);
            _isRuning = false;
        }

        static void* ThreadRoutie(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }

    public:
        Thread(std::string& name, func_t fun)
            :_name(name),_fun(fun)
        {}

        ~Thread()
        {}

        // 启动
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, ThreadRoutie, this);
            return n == 0 ? true : false;
        }

        // 终止
        void Stop()
        {
            if(_isRuning)
            {
                pthread_cancel(_tid);
                _isRuning = false;
            }
        }

        // 等待
        void Jion()
        {
            pthread_join(_tid, nullptr);
        }

        // 获取线程的状态
        std::string Status()
        {
            return _isRuning == false ? "sleep" : "running";
        }

        // 获取线程名
        std::string Name()
        {
            return _name;
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isRuning;
        func_t _fun;
    };
}